package cn.xiaobai.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author yangdaji
 * @Date 2022/11/8 0008
 * @PackageName xiaobai.utils
 * @ClassName SpringContextUtils
 */
@Slf4j
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取spring配置的对象
     *
     * @param className 类对象
     * @return
     */
    public static <V> V getBean(Class<V> className) {
        Object bean = applicationContext.getBean(className);
        try {
            return (V) bean;
        } catch (Exception e) {
            log.error("类型转换失败,请检查类型是否正确: {}", e.getMessage());
            return null;
        }
    }
}
